package com.example.testapp;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.testapp.api.ApiClient;
import com.example.testapp.api.ApiService;
import com.example.testapp.model.LoginRequest;
import com.example.testapp.model.UserResponse;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends Activity {
    private static final String TAG = "LoginActivity";
    private EditText etPhoneNumber, etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private CheckBox agreementCheckbox;
    private TextView agreementText;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        sharedPreferences = getSharedPreferences("AppPrefs", MODE_PRIVATE);

        // 检查是否已经登录
        if (isLoggedIn()) {
            int userId = sharedPreferences.getInt("userId", 0);
            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
            intent.putExtra("userId", userId);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            // 添加日志记录
            Log.d(TAG, "用户已登录，跳转到 HomeActivity，用户 ID: " + userId);
            startActivity(intent);
            finish();
            return;
        }

        // 初始化视图
        etPhoneNumber = findViewById(R.id.phone_number);
        etPassword = findViewById(R.id.password);
        btnLogin = findViewById(R.id.login_button);
        tvRegister = findViewById(R.id.register_text);
        // 服务协议
        TextView agreementText1 = findViewById(R.id.agreement_text1);
        // 隐私保护协议
        TextView agreementText2 = findViewById(R.id.agreement_text2);
        agreementCheckbox = findViewById(R.id.agreement_checkbox);

        // 添加手机号输入监听
        etPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11) {
                    etPassword.requestFocus(); // 自动跳转到密码输入框
                }
            }
        });

        // 设置服务协议和隐私保护协议的点击事件
        agreementText1.setOnClickListener(v -> openAgreement("https://gitee.com/wys_666/android-frontend"));
        agreementText2.setOnClickListener(v -> openAgreement("https://gitee.com/wys_666/android-backend"));

        // 设置勾选监听
        agreementCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 移除canCancel标志，允许自由勾选和取消
                if (isChecked) {
                    // 勾选时显示提示
                    Toast.makeText(LoginActivity.this, "已阅读并同意服务协议", Toast.LENGTH_SHORT).show();
                } else {
                    // 取消勾选时显示提示
                    Toast.makeText(LoginActivity.this, "已取消同意服务协议", Toast.LENGTH_SHORT).show();
                }
            }
        });

        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyboard();

                String phoneNumber = etPhoneNumber.getText().toString().trim();
                String password = etPassword.getText().toString().trim();

                // 验证输入
                if (phoneNumber.isEmpty() || password.isEmpty()) {
                    Toast.makeText(LoginActivity.this, "请输入手机号和密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 验证协议勾选
                if (!agreementCheckbox.isChecked()) {
                    Toast.makeText(LoginActivity.this, "请阅读并同意服务协议", Toast.LENGTH_SHORT).show();
                    return;
                }

                btnLogin.setEnabled(false);

                // 执行登录请求
                ApiService apiService = ApiClient.getClient().create(ApiService.class);
                LoginRequest request = new LoginRequest(phoneNumber, password);

                apiService.login(request).enqueue(new Callback<UserResponse>() {
                    @Override
                    public void onResponse(@NonNull Call<UserResponse> call, @NonNull Response<UserResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            UserResponse user = response.body();
                            Toast.makeText(LoginActivity.this, "登录成功：" + user.getUsername(), Toast.LENGTH_SHORT).show();

                            // 保存登录信息
                            saveLoginInfo(user.getId(), user.getToken());

                            // 跳转到主界面并清除栈
                            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                            intent.putExtra("userId", user.getId());
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            Log.d(TAG, "用户登录成功，跳转到 HomeActivity，用户 ID: " + user.getId());
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(LoginActivity.this, "登录失败，请检查账号密码", Toast.LENGTH_SHORT).show();
                        }
                        btnLogin.setEnabled(true);
                    }

                    @Override
                    public void onFailure(@NonNull Call<UserResponse> call, @NonNull Throwable t) {
                        Toast.makeText(LoginActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                        btnLogin.setEnabled(true);
                    }
                });
            }
        });

        // 注册链接点击事件
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    // 保存登录信息到SharedPreferences的方法
    private void saveLoginInfo(int userId, String token) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("userId", userId);
        editor.putString("auth_token", token);
        editor.apply();
    }

    // 检查是否已经登录
    private boolean isLoggedIn() {
        return sharedPreferences.contains("userId") && sharedPreferences.contains("auth_token");
    }

    // 点击布局时让输入框失去焦点
    public void clearFocusOnClick(View view) {
        etPhoneNumber.clearFocus();
        etPassword.clearFocus();
        hideKeyboard();
    }

    // 隐藏软键盘的方法
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = getCurrentFocus();
        if (view == null) {
            view = new View(this);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    // 打开浏览器的方法
    private void openAgreement(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
    }
}